﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace Commander
{
    /// <summary>
    /// Клас для роботи з файловой системой
    /// </summary>
    class WorkDir
    {
        /// <summary>
        /// Метод для удаления файла
        /// </summary>
        /// <param name="FileName">имя файла</param>
        /// <returns></returns>
        public static bool DeleteFile(string FileName)
        {
            if (!File.Exists(FileName)) return true;
            try
            {
                FileInfo f = new FileInfo(FileName);
                f.IsReadOnly = false;
                f.Delete();
            }
            catch { }

            return !File.Exists(FileName);
        }

        /// <summary>
        /// Метод для удаления папки з ее внутреним содержанием
        /// </summary>
        /// <param name="FolderName">имя папки</param>
        /// <returns></returns>
        public static bool DeleteDir(string FolderName)
        {
            if (!Directory.Exists(FolderName))
            {
                return true;
            }
            foreach (string s in Directory.GetFiles(FolderName))
            {
                DeleteFile(s);
            }

            foreach (string s in Directory.GetDirectories(FolderName))
            {
                try
                {
                    DeleteDir(s);
                }
                catch { }
            }
            try
            {
                Directory.Delete(FolderName);
            }
            catch { }
            return !Directory.Exists(FolderName);
        }

        public static bool CopyFile(string oldName, string newName)
        {
            if (!Directory.Exists(Path.GetDirectoryName(newName)))
            {
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(newName));
                }
                catch
                {
                    return false;
                }
            }
            else if (!DeleteFile(newName))
            {
                return false;
            }
            try
            {
                File.Copy(oldName, newName);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static void CopyDir(string oldName, string newName)
        {
            if (Directory.Exists(newName)) DeleteDir(newName);
            Directory.CreateDirectory(newName);

            foreach (string s in Directory.GetFiles(oldName))
            {
                CopyFile(s, newName + "\\" + Path.GetFileName(s));
            }

            foreach (string s in Directory.GetDirectories(oldName))
            {
                CopyDir(s, newName + "\\" + Path.GetFileName(s));
            }
        }
    }
}
